<!-- 搜索 -->
<template>
    <div>
        <app-head :searchInput="searchValue"></app-head>    
        <app-body>
                <div class="search-content">
                    <div class="no-match" v-if="idleList.length === 0">暂无匹配的二手物品</div>
					<!-- 排序控制界面 -->
					            <!-- <div class="sort-controls">
					                <el-select v-model="sortRule" placeholder="选择排序规则">
					                    <el-option label="价格" value="price"></el-option>
					                    <el-option label="销量" value="sales"></el-option>
					                </el-select>
					                <el-select v-model="sortOrder" placeholder="选择排序顺序">
					                    <el-option label="升序" value="asc"></el-option>
					                    <el-option label="降序" value="desc"></el-option>
					                </el-select>
					            </div> --> 
                    <!-- 行布局组件  里面放置列组件  间距30
                    <el-row :gutter="30">
                        <!-- 列布局组件  24栅格  占6栅格 -->
                        <el-col :span="6" v-for="(idle, index) in idleList" :key="index">
                          
                            <!-- 商品卡片 -->
                            <div class="idle-card" @click="toDetails(idle)">
                                
                                <!-- 商品图片 -->
                                <el-image class="idle-image" :src="$store.state.baseApi + idle.imgUrl" fit="contain">
                                    <!-- 没图 -->
                                    <div slot="error" class="image-slot">
                                        <i class="el-icon-picture-outline">无图</i>
                                    </div>
                                </el-image>

                                <!-- 商品名称 -->
                                <div class="idle-title">
                                    {{idle.idleName}}
                                </div>

                                <!-- 商品详情 钱和地址 -->
                                <el-row class="idle-details">
                                    <el-col :span="12">
                                        <div class="idle-prive">￥{{idle.idlePrice}}</div>
                                    </el-col>
                                    <el-col :span="12">
                                        <div class="idle-num">数量:{{ idle.idleNum }}</div>
                                    </el-col>
                                    <el-col :span="12">
                                        <div class="idle-place">{{idle.idlePlace}}</div>
                                    </el-col>
                                </el-row>

                                <!-- 商品上架时间 -->
                                <div class="idle-time">{{idle.timeStr}}</div>
                               
                                <!-- 商家信息 -->
                                <div class="user-info">
                                    <el-image class="user-avatar" :src="$store.state.baseApi + idle.user.avatar" fit="contain">
                                        <div slot="error" class="image-slot">
                                            <i class="el-icon-picture-outline">无图</i>
                                        </div>
                                    </el-image>
                                    <div class="user-nickname">{{idle.user.nickname}}</div>
                                </div>

                            </div>
                        </el-col>
                    </el-row>
                </div>
                
                <!-- 分页 -->
                <div class="fenye">  <!-- 事件监听器 -->                               <!-- 双向数据绑定 -->
                    <el-pagination  background @current-change="handleCurrentChange" :current-page.sync="currentPage"
                        :page-size="8" layout="prev, pager, next, jumper" :total="totalItem"> <!-- prev, pager, next, jumper 分别表示上一页按钮、页码、下一页按钮、跳转输入框。 -->
                    </el-pagination>
                </div>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppMeHeader.vue';
    import AppBody from '../common/AppPageBody.vue';
    import AppFoot from '../common/AppFoot.vue';

    export default {
        name: "search",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                idleList: [],
                currentPage: 1,
                searchValue: '',
                totalItem: 1,
				sortRule: 'price', // 默认排序规则为价格
				sortOrder: 'asc',  // 默认排序顺序为升序
            };
        },
		computed: {
		        sortedIdleList() {
		            let list = [...this.idleList]; // 复制一份商品列表，避免修改原始数据
		            let compareFn;
		            switch (this.sortRule) {
		                case 'price':
		                    compareFn = (a, b) => a.idlePrice - b.idlePrice;
		                    break;
		                case 'sales':
		                    compareFn = (a, b) => a.idleNum - b.idleNum; // 假设 idleNum 表示销量
		                    break;
		                default:
		                    compareFn = (a, b) => a.idlePrice - b.idlePrice;
		            }
		
		            if (this.sortOrder === 'desc') {
		                compareFn = (a, b) => compareFn(b, a);
		            }
		
		            return list.sort(compareFn);
		        }
		    },
        created() {//生命周期钩子  实例创建完后立即调用
            this.findIdleTiem(1, this.$route.query.searchValue);//调用函数findIdleTiem
            this.searchValue = this.$route.query.searchValue;
        },
        watch: {//监听路由变化，当路由发生变化时，它会根据新路由的查询参数来更新 searchValue 的值并调用 findIdleTiem 方法。
            $route(to, from) {
                this.searchValue = to.query.searchValue;//赋值
                this.findIdleTiem(to.query.page, to.query.searchValue);
            }
        },
        methods: {//从服务器获取数据并处理数据
            findIdleTiem(page, findValue) {//查找闲置物品 俩参数 page:要获取的页数  findValue指定搜索的值
                this.$api.findIdleTiem({//调用api接口，向服务器发送请求，请求查找闲置物品
                    page: page,
                    nums: 8,//每页显示8个
                    findValue: findValue
                }).then(res => {//服务器成功返回数据
                    console.log(res);
                    let list = res.data.list;//获取数据
                    for (let i = 0; i < list.length; i++) {//遍历数据
                        list[i].timeStr = list[i].releaseTime.substring(0, 10) + " " + list[i].releaseTime.substring(11, 19);//时间格式化
                        let pictureList = JSON.parse(list[i].pictureList);//图片列表
                        list[i].imgUrl = pictureList.length > 0 ? pictureList[0] : '';//图片地址
                        list = list.filter(item => item.idleNum >= 1); //过滤数量小于1的商品（小于1被卖完了）
                    }
                    this.idleList = list;//过滤后的列表进行赋值
                    this.totalItem = res.data.count;//总数
                }).catch(e => {//服务器返回数据失败，打印到控制台
                    console.log(e);
                });
            },
            handleCurrentChange(val) {//分页  val页码
                console.log(`当前页: ${val}`);//输出当前页
                this.$router.replace({ query: { page: val, searchValue: this.searchValue } });//改变页码，replace跳转
            },
            toDetails(idle) {//跳转到指定商品详情页
                this.$router.push({ path: '/details', query: { id: idle.id } });
            }
        }
    };
</script>


<style scoped>
    .idle-card {
        height: 300px;
        border: #eeeeee solid 1px;
        margin-bottom: 15px;
        cursor: pointer;
    }

    .fenye {
        display: flex;
        justify-content: center;
        height: 60px;
        align-items: center;
        position: fixed;
        bottom: 30px;
        left: 50%;
        transform: translateX(-50%);
    }
    .idle-image {
        width: 100%;
        height: 160px;
    }
    .idle-title {
        font-size: 18px;
        font-weight: 600;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin: 10px;
    }

    .idle-prive {
        font-size: 16px;
        color: red;
    }

    .idle-place {
        font-size: 13px;
        color: #666666;
        float: right;
        padding-right: 20px;

    }

    .idle-time {
        color: #666666;
        font-size: 12px;
        margin: 0 10px;
    }

    .user-nickname {
        color: #999999;
        font-size: 12px;
        display: flex;
        align-items: center;
        height: 30px;
        padding-left: 10px;
    }

    .user-info {
        padding: 5px 10px;
        height: 30px;
        display: flex;
    }
    .no-match{
        text-align: center;
        font-size: 20px;
        color: #999999;
        margin-top: 100px;
    }
	.sort-controls {
	    display: flex;
	    margin-bottom: 15px;
	}
	
	.sort-controls .el-select {
	    margin-right: 10px;
	}
</style>